﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;

namespace mesoBoard.Data.Repositories
{
    public class CategoryRepository : ICategoryRepository
    {
        private mbEntities db;
        
        public CategoryRepository(mbEntities mbDataContext)
        {
            this.db = mbDataContext;
        }

        public IEnumerable<Category> GetCategories()
        {
            return db.Categories.AsEnumerable();
        }

        public Category GetCategory(int CategoryID)
        {
            return db.Categories.FirstOrDefault(x => x.CategoryID == CategoryID);
        }

        public void SubmitChanges()
        {
            db.SaveChanges();
        }

        public void UpdateCategory(Category TheCategory)
        {
            if (TheCategory.EntityKey == null)
                TheCategory.EntityKey = ((Category)db.GetObjectByKey(new System.Data.EntityKey("mbEntities.Categories", "CategoryID", TheCategory.CategoryID))).EntityKey;

            db.Categories.ApplyCurrentValues(TheCategory);
            db.SaveChanges();
        }

        public void CreateCategory(Category TheCat)
        {
            TheCat.Order = db.Categories.Count() > 0 ? db.Categories.OrderByDescending(x => x.Order).FirstOrDefault().Order + 1 : 1;
            db.Categories.AddObject(TheCat);
            db.SaveChanges();
        }

        public void DeleteCategory(Category TheCat)
        {
            db.Categories.DeleteObject(GetCategory(TheCat.CategoryID));
            db.SaveChanges();
            /*IEnumerable<Thread> Threads = db.Threads.Where(x => x.Forum.CategoryID == TheCat.CategoryID);
            foreach (Thread t in Threads)
            {
                db.ThreadViewStamps.DeleteAllOnSubmit(db.ThreadViewStamps.Where(x => x.ThreadID == t.ThreadID));
                db.Attachments.DeleteAllOnSubmit(db.Attachments.Where(x => x.Post.ThreadID == t.ThreadID));
                db.Posts.DeleteAllOnSubmit(t.Posts);
                if (t.Poll != null)
                {
                    db.PollOptions.DeleteAllOnSubmit(db.PollOptions.Where(x => x.PollID == t.Poll.PollID));
                    db.PollVotes.DeleteAllOnSubmit(db.PollVotes.Where(x => x.PollID == t.Poll.PollID));
                    db.Polls.DeleteObject(t.Poll);
                }
            }
            db.SaveChanges();
            foreach (Forum f in TheCat.Forums)
            {
                db.ForumPermissions.DeleteAllOnSubmit(db.ForumPermissions.Where(x => x.Forum.CategoryID == TheCat.CategoryID));
            }
            db.Threads.DeleteAllOnSubmit(Threads);
            db.SaveChanges();
            db.Forums.DeleteAllOnSubmit(TheCat.Forums);
            db.SaveChanges();
            db.Categories.DeleteObject(TheCat);
            db.SaveChanges();*/
        }
    }
}
